﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.Bll;
using System.Web.UI.DataVisualization.Charting;

using System.Drawing;

public partial class Templates_Audit_Default : LoggedInPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int? id = null;
            if (Request.QueryString["Id"] != null)
            {
                try
                {
                    id = int.Parse((string)Request.QueryString["Id"]);
                }
                catch { }
            }

            var auditfactory = new AuditFactory();
            
            //try getting for id
            if (id != null)
            {
                _Audit = auditfactory.GetByIdAndUserId(id.Value, User.Identity.User.Id);
            }


            //if its null get the latest completed
            if (_Audit == null)
            {
                _Audit = auditfactory.GetLatestCompletedByUserId(AcmsUser.User.Id);
            }

            if (_Audit == null)
            {
                if (auditfactory.GetCurrentForUserId(AcmsUser.User.Id) != null)
                {
                    AcmsContext.RedirectToUrl("~/MyCO2/ContinueAudit.aspx", this);
                }
                else
                {
                    AcmsContext.RedirectToUrl("~/MyCO2/CreateAudit.aspx", this);
                }

            }
            else if (!_Audit.Completed)
            {
                AcmsContext.RedirectToUrl("~/MyCO2/ContinueAudit.aspx", this);
            }

            else
            {
                _AuditId = _Audit.Id;
                lblTitle.Text = string.Format(" - {0:dd MMMM yyyy}", _Audit.EndDate);
            }
            
            msChartSections.PaletteCustomColors = new Color[] {
                Color.FromArgb(230, ColorTranslator.FromHtml("#58595b")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#cc3399")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#00aeef")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#336699")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#c2bcb6")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#ec008c"))
                //ColorTranslator.FromHtml("#efebe0")
            };

            msChartAverages.PaletteCustomColors = new Color[] {
                Color.FromArgb(230, ColorTranslator.FromHtml("#58595b")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#336699")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#cc3399")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#00aeef")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#c2bcb6")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#ec008c"))
                //ColorTranslator.FromHtml("#efebe0")
            };


            msChartAllAudits.PaletteCustomColors = new Color[] {
                
                Color.FromArgb(230, ColorTranslator.FromHtml("#58595b")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#cc3399")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#00aeef")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#336699")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#c2bcb6")),
                Color.FromArgb(230, ColorTranslator.FromHtml("#ec008c"))

                //ColorTranslator.FromHtml("#efebe0")
            };
            
            DataBind();

        }
    }
    
    public override void DataBind()
    {
        var factory = new CarbonExchange.Bll.UserSectionFactory();
        var userSections = factory.GetAllByAuditId(Audit.Id).ToList();

        // Sections
        // Populate series data
        var sectionsYValues = userSections.Select(userSection => userSection.Footprint > 0 ? userSection.Footprint : 0).ToArray();
        var sectionsXValues = userSections.Select(userSection => userSection.SectionName).ToArray();

        msChartSections.Series["Default"].Points.Clear();
        msChartSections.Series["Default"].Points.DataBindXY(sectionsXValues, sectionsYValues);
       // msChartSections.Series["Default"].ChartType = SeriesChartType.Doughnut;

        msChartSections.Series["Default"]["PieLabelStyle"] = "Disabled";
        msChartSections.Series["Default"]["PieDrawingStyle"] = "SoftEdge";
        msChartSections.Series["Default"]["DoughnutRadius"] = "70";

       
        

        //Household vs Average
        var householdYValues = userSections.Select(userSection => userSection.Footprint).ToArray();
        var householdXValues = userSections.Select(userSection => userSection.SectionName).ToArray();
        var averages = factory.GetAveragesBySiteId(AcmsContext.SiteId).ToArray();
        var averagesYValues = householdXValues.Select(sectionName => averages.Where(average => average.SectionName == sectionName).Select(x => x.Footprint).FirstOrDefault()).ToArray();

        msChartAverages.ChartAreas[0].AxisX.Interval = 1; 
        
        msChartAverages.Series["Household"].Points.Clear();
        msChartAverages.Series["Household"]["DrawingStyle"] = "Default";
        msChartAverages.Series["Household"].Points.DataBindXY(householdXValues, householdYValues);

        msChartAverages.Series["Average"].Points.Clear();
        msChartAverages.Series["Average"]["DrawingStyle"] = "Default";
        msChartAverages.Series["Average"].Points.DataBindXY(householdXValues, averagesYValues);

        //msChartAverages.Series["Average"]["PointWidth"] = "1";
        //msChartAverages.Series["Household"]["PointWidth"] = "1";

        //compair all
        var sections = new SectionFactory().GetAll();
        var allAudits = factory.GetAllByUserId(User.Identity.User.Id).GroupBy(x => x.AuditDate).OrderByDescending(x => x.Key).Take(5).Reverse().ToList();
        msChartAllAudits.Series.Clear();
        foreach (var section in sections)
        {
            msChartAllAudits.Legends[0].LegendItemOrder = LegendItemOrder.SameAsSeriesOrder;
            msChartAllAudits.Series.Add(section.Name);
            
                             

            msChartAllAudits.Series.Last().ChartType = SeriesChartType.StackedColumn;
            msChartAllAudits.Series.Last()["PointWidth"] = "0.8";
            msChartAllAudits.Series.Last()["DrawingStyle"] = "Default";

            msChartAllAudits.Series.Last().ToolTip = "#AXISLABEL : #SERIESNAME : #VAL{#,##0} KgCO2 #LABEL ";//"#SERIESNAME : #VAL{#,##0} KgCO2 #LABEL ";
            
            var tmpData = allAudits.Select(x => new { Key = x.Key, Value = x.Where(y => y.SectionId == section.Id).Select(y => y.Footprint).FirstOrDefault() }).ToArray();
            foreach (var t in tmpData)
            {
                var dataPoint = new DataPoint();
                dataPoint.IsValueShownAsLabel = false;
                dataPoint.SetValueXY(t.Key.ToShortDateString(), t.Value);
                msChartAllAudits.Series.Last().Points.Add(dataPoint);

            }
        }
        msChartAllAudits.ChartAreas[0].AxisX.Interval = 1; 
        base.DataBind();
    }

    private int _AuditId;
    private Audit _Audit;
    protected Audit Audit
    {
        get
        {
            if(_Audit == null && _AuditId > 0)
            {
                _Audit = new AuditFactory().GetLatestForUserId(AcmsUser.User.Id);
            }
            return _Audit;
        }
    }

    protected override object SaveViewState()
    {
        ViewState["AuditId"] = _AuditId;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        _AuditId = (int)ViewState["AuditId"];

    }
}
